package aufgabenserie_1;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Caesar {
	
	public static void main(String[] vargs){
//		writeTest();
		caesar_crypt(new File("plaintext.txt"), new File("chiffre"), true, 160);
		System.out.println("--------------------------------");
		caesar_crypt(new File("chiffre"), new File("decrypted.txt"), false, 160);
		
		System.out.println("\n"+ -5%256);
	}
	
	public static void writeTest(){
		FileWriter fw;
		try {
			fw = new FileWriter("Test");
			for (int i = 0; i < 20; i++) {
				fw.append((char)i);
			}
			fw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	public static void caesar_crypt(File input, File output, boolean encrypt, int key){
		try {
			if(encrypt){
				
					FileReader fr = new FileReader(input);
					FileWriter fw = new FileWriter(output);
					while(fr.ready()){
						int tmp = (char) fr.read();
						System.out.print(tmp+"TO");
						fw.append((char) ( (tmp + key) % 256));
						System.out.println( (tmp + key)% 256+" ");
					}
					fw.close();
				
			}else{
				
				FileReader fr = new FileReader(input);
				FileWriter fw = new FileWriter(output);
				while(fr.ready()){
					int tmp = (char) fr.read();
					System.out.print(tmp+"TO");
					if(tmp-key < 0){
						fw.write(256 + (tmp-key));
						System.out.println( 256 + (tmp-key)+" ");
					}else{
						fw.write( (tmp-key) % 256);
						System.out.println( (tmp-key) % 256+" ");
					}
					
					
				}
				fw.close();
				
			}
		
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
